#include "serial_manager.h"
#include "serial_data.h"
#include "serial_help_fun.h"

#define BD_ADDR_LEN 6





bool check_cmd_infor(uint8_t cmd, uint8_t option, uint8_t *pdata, uint16_t len, server_cmd_t *outcmd)
{
	bool ret = false;

	if (outcmd != NULL)
	{
		//清空
		memset(outcmd, 0, sizeof(server_cmd_t));
		uint16_t pos = 0;
		//mac 地址
		memcpy(outcmd->addr, pdata + pos, BD_ADDR_LEN);
		pos += BD_ADDR_LEN;
		//index
		uint32_t index = 0;
		index += (pdata[pos++] << 24);
		index += (pdata[pos++] << 16);
		index += (pdata[pos++] << 8);
		index += (pdata[pos++] << 0);
		outcmd->index = index;
		//type
		outcmd->type = pdata[pos++];
		//数据长度
		outcmd->length += (pdata[pos++] << 8);
		outcmd->length += (pdata[pos++] << 0);

		if (!((outcmd->length + pos) == len))
		{
			return ret;
		}
		outcmd->pdata = &pdata[pos];
		ret = true;
	}
	return ret;
}

int rx_data_analyse_do(uint8_t cmd, uint8_t option, uint8_t *pdata, uint16_t len)
{

	server_cmd_t cmd_ins;
	bool wrap_valid = check_cmd_infor(cmd, option, pdata, len, &cmd_ins);
	if (!wrap_valid)
	{
		printf("\n\tXX@@ ERR->[%s] check_cmd_infor Error,wrap valid\n", __func__);
		return -2;
	}

    printf("@@@@@@@@@@@ cmd :%d, type:%d\n",cmd, cmd_ins.type);

    if(cmd_ins.type != 0x30)
    {
        print_data(pdata,len);
        return 2;
    }

    return 1;

}



int serial_manager(RingBuffer *buf)
{
    uint16_t size;
    int ret;

	ComStream_t inStreamreseave;
	uint8_t read_buftemp[RECV_BUFFER_SIZE];
	uint8_t read_buftest[RECV_BUFFER_SIZE];
	UnPack_t pResultreseave;

BEGIN:
	size = user_buffer_item_count(buf); // get used buffer size
	memset(read_buftemp, 0, sizeof(read_buftemp));
	memset(read_buftest, 0, sizeof(read_buftest));
	if (size > 0)
	{

		inStreamreseave.nLenOfBuf = size;

		inStreamreseave.pBuffer = read_buftemp;
		user_buffer_read_items(buf, inStreamreseave.pBuffer, inStreamreseave.nLenOfBuf);
		// ESP_LOG_BUFFER_HEXDUMP(TAG,  inStream.pBuffer, inStream.nLenOfBuf, ESP_LOG_INFO);
		pResultreseave.pData = read_buftest;
		PTL_STATUS rt;
		rt = uart_unpack(&inStreamreseave, &pResultreseave);

        printf("@@ %s rt:%d \n",__func__, rt);

		if (PTL_HEAD_ERROR == rt)
		{
			user_buffer_release_items(buf, size);
		}
		else if (PTL_LENGTH_ERROR == rt)
		{
			user_buffer_release_items(buf, pResultreseave.indexOfHead);
		}
		else if ((PTL_CHECKSUM_ERROR == rt) || (PTL_TAIL_ERROR == rt) || (PTL_DATA_ERROR == rt))
		{
			user_buffer_release_items(buf, (pResultreseave.indexOfTail + 1));
			//receive_uart_data_slot(buffer,port);
			goto BEGIN;
		}
		else if (PTL_NO_ERROR == rt)
		{
			ret = rx_data_analyse_do(pResultreseave.cmdID, pResultreseave.option, pResultreseave.pData, pResultreseave.lenOfData);
			user_buffer_release_items(buf, (pResultreseave.indexOfTail + 1));
            return ret;
			//goto BEGIN;
		}
	}

    return 0;
}